# coding=utf-8
# !/usr/bin/python
# base on UndCover
# modified by eaudouce
import os, sys, json, requests, time, base64
sys.path.append('..')
from base.spider import Spider

class Spider(Spider):  # 元类 默认的元类 type
    site_name = 'xk_哔哩'
    cookies = ''
    headers = {
        'Accept-Encoding': 'gzip, deflate',
        'Referer': 'https://www.bilibili.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0'
    }
    config = {
        'player': {},
        'filter': {},
        'class': [
            {'type_name': '热点资讯', 'type_id': '203'},
            {'type_name': '环球资讯', 'type_id': '204'},
            {'type_name': '美食制作', 'type_id': '76'},
            {'type_name': '田园美食', 'type_id': '214'},
            {'type_name': '亲子', 'type_id': '254'},
            {'type_name': '健身', 'type_id': '164'},
            {'type_name': '音乐现场', 'type_id': '29'},
            {'type_name': 'MV', 'type_id': '193'},
            {'type_name': '科学科普', 'type_id': '201'},
            {'type_name': '社科·法律·心理', 'type_id': '124'},
            {'type_name': '人文历史', 'type_id': '228'},
            {'type_name': '财经商业', 'type_id': '207'},
            {'type_name': '校园学习', 'type_id': '208'}
        ]
    }

    def getName(self):
        return self.site_name

    def init(self, extend=''):
        print('============{0}============'.format(extend))
        pass

    def isVideoFormat(self, url):
        pass

    def manualVideoCheck(self):
        pass

    def homeContent(self, filter):
        result = {'class': self.config['class']}
        if (filter):
            result['filters'] = self.config['filter']
        return result

    def homeVideoContent(self):
        result = {
            'list': []
        }
        return result

    def getCookie(self):
        rsp = self.fetch('https://www.bilibili.com/', headers=self.headers)
        self.cookies = rsp.cookies
        return rsp.cookies

    def categoryContent(self, tid, pg, filter, extend):
        limit = 30
        result = {
            'list': [],
            'page': pg,
            'pagecount': 0,
            'limit': limit,
            'total': 0
        }

        time_from = time.strftime('%Y%m%d', time.localtime(time.time() - 3600*24*14))
        time_to = time.strftime('%Y%m%d', time.localtime())
        url = 'https://api.bilibili.com/x/web-interface/newlist_rank?main_ver=v3&search_type=video&view_type=hot_rank&copy_right=-1&new_web_tag=1&order=click&cate_id={}&page={}&pagesize={}&time_from={}&time_to={}'.format(tid, pg, limit, time_from, time_to)
        if len(self.cookies) <= 0:
            self.getCookie()
        rsp = self.fetch(url, cookies=self.cookies, headers=self.headers)
        jo = json.loads(rsp.text)
        if jo['code'] != 0:
            return result

        videos = []
        vodList = jo['data']['result']
        for vod in vodList:
            aid = str(vod['id']).strip()
            title = vod['title'].replace('<em class="keyword">', '').replace('</em>', '').replace('&quot;', '"')
            img = 'https:' + vod['pic'].strip()
            remark = self.formatDuration(vod['duration'])
            videos.append({
                'vod_id': aid,
                'vod_name': title,
                'vod_pic': img,
                'vod_remarks': remark
            })
        result['list'] = videos
        result['page'] = pg
        result['pagecount'] = int(jo['data']['numPages'])
        result['limit'] = limit
        result['total'] = int(jo['data']['numResults'])
        return result

    def cleanSpace(self, str):
        return str.replace('\n', '').replace('\t', '').replace('\r', '').replace(' ', '')

    def detailContent(self, array):
        aid = array[0]
        url = 'https://api.bilibili.com/x/web-interface/view?aid={0}'.format(aid)
        if len(self.cookies) <= 0:
            self.getCookie()
        rsp = self.fetch(url, headers=self.headers, cookies=self.cookies)
        jRoot = json.loads(rsp.text)
        jo = jRoot['data']
        title = jo['title'].replace('<em class="keyword">', '').replace('</em>', '').replace('&quot;', '"')
        pic = jo['pic']
        desc = jo['desc']
        timeArray = time.localtime(jo['pubdate'])
        year = str(time.strftime('%Y', timeArray))
        director = jo['owner']['name']
        typeName = jo['tname']
        remark = self.formatDuration(jo['duration'])
        vod = {
            'vod_id': aid,
            'vod_name': title,
            'vod_pic': pic,
            'type_name': typeName,
            'vod_year': year,
            'vod_area': '',
            'vod_remarks': remark,
            'vod_actor': '',
            'vod_director': director,
            'vod_content': desc
        }
        ja = jo['pages']
        playUrl = ''
        for tmpJo in ja:
            cid = tmpJo['cid']
            part = tmpJo['part'].replace('#', '-')
            playUrl = playUrl + '{0}${1}_{2}#'.format(part, aid, cid)

        vod['vod_play_from'] = self.site_name
        vod['vod_play_url'] = playUrl.strip('#')

        result = {
            'list': [
                vod
            ]
        }
        return result

    def searchContent(self, key, quick):
        url = 'https://api.bilibili.com/x/web-interface/search/type?search_type=video&keyword={0}'.format(key)
        if len(self.cookies) <= 0:
            self.getCookie()
        rsp = self.fetch(url, cookies=self.cookies, headers=self.headers)
        content = rsp.text
        jo = json.loads(content)
        if jo['code'] != 0:
            rspRetry = self.fetch(url, cookies=self.getCookie(), headers=self.headers)
            content = rspRetry.text
        jo = json.loads(content)
        videos = []
        vodList = jo['data']['result']
        for vod in vodList:
            aid = str(vod['aid']).strip()
            title = vod['title'].replace('<em class="keyword">', '').replace('</em>', '').replace('&quot;', '"')
            img = 'https:' + vod['pic'].strip()
            remark = self.formatDuration(vod['duration'])
            videos.append({
                'vod_id': aid,
                'vod_name': title,
                'vod_pic': img,
                'vod_remarks': remark
            })
        result = {
            'list': videos
        }
        return result

    def playerContent(self, flag, id, vipFlags):
        result = {}

        ids = id.split('_')
        url = 'https://api.bilibili.com:443/x/player/playurl?avid={0}&cid={1}&qn=116'.format(ids[0], ids[1])
        if len(self.cookies) <= 0:
            self.getCookie()
        rsp = self.fetch(url, cookies=self.cookies, headers=self.headers)
        jRoot = json.loads(rsp.text)
        jo = jRoot['data']
        ja = jo['durl']

        maxSize = -1
        position = -1
        for i in range(len(ja)):
            tmpJo = ja[i]
            if maxSize < int(tmpJo['size']):
                maxSize = int(tmpJo['size'])
                position = i

        url = ''
        if len(ja) > 0:
            if position == -1:
                position = 0
            url = ja[position]['url']

        header = self.headers
        cookies_str = ''
        cookies_dict = self.cookies.get_dict()
        for i in cookies_dict:
            cookies_str += i + '=' + cookies_dict[i] + '; '
        header['Cookie'] = cookies_str
        result['parse'] = 0
        result['playUrl'] = ''
        result['url'] = url
        result['header'] = header
        result['contentType'] = 'video/x-flv'
        return result

    def localProxy(self, param):
        return [200, 'video/MP2T', action, '']

    def formatDuration(self, duration):
        result = []
        if str(duration).isdigit() == False:
            return duration
        duration = int(duration)
        for i in range(0, 3):
            duration = divmod(duration, 60)
            result.insert(0, '{}'.format(duration[1]).zfill(2))
            duration = duration[0]
        if result[0] == '00':
            return ':'.join(result[1:])
        else:
            return ':'.join(result).lstrip('0')
